import React, {PureComponent} from 'react';
import {Button, Checkbox, Form, Input, Modal, Select, Steps, Tree,} from 'antd';
import DescriptionList from '@/components/DescriptionList';
import {nameMaxLength, remarkMaxLength} from '@/utils/rule';
import UserSelect from '../../../Common/UserSelect';
import {connect} from 'dva';

const CheckboxGroup = Checkbox.Group;
const {Description} = DescriptionList;
const FormItem = Form.Item;
const {Step} = Steps;
const {TextArea} = Input;
const {Option} = Select;
const {TreeNode} = Tree;
const RightOptions = [
  {label: '加密', value: '1'},
  {label: '脱敏', value: '3'},
  {label: '转PDF', value: '4'},
  {label: '水印', value: '5'},
];

@connect(({loading}) => ({
  submitting: loading.effects['privateFileModel/addFlowApply'],
}))
/**
 * 个人文件，流转申请页面
 */
@Form.create()
class FlowCreateForm extends PureComponent {
  static defaultProps = {
    handleFlow: () => {
    },
    handleFlowModalVisible: () => {
    },
    records: [],
  };
  formLayout = {
    labelCol: {span: 7},
    wrapperCol: {span: 13},
  };

  constructor(props) {
    super(props);
    this.state = {
      orgId: '',
      selectedUserRows: [],
      formVals: {
        // id: props.record.id,
        // dirName: props.record.dirName,
        applyTitle: "",
        applyReason: "",
        rightConfig: "",
        toUserCodes: "",
      },
      currentStep: 0,
      selectedRowKeys: [],

    };

    this.formLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 18},
    };
  }

  handleNext = currentStep => {

    const {form, handleFlow, records} = this.props;
    const {formVals: oldValue, selectedUserRows} = this.state;


    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = {...oldValue, ...fieldsValue};
      this.setState(
        {
          formVals,
        },
        () => {
          if (currentStep < 2) {
            this.forward();
          } else {
            handleFlow(formVals, records, selectedUserRows);
          }
        }
      );
    });
  };

  backward = () => {
    const {currentStep} = this.state;
    this.setState({
      currentStep: currentStep - 1,
    });
  };

  forward = () => {
    const {currentStep} = this.state;
    this.setState({
      currentStep: currentStep + 1,
    });
  };


  onSelect = v => {
    const value = v[0];
    const {onFlowOrgChange} = this.props;
    this.setState({orgId: value});
    onFlowOrgChange(value);
  }

  handleSelectUserRows = (rows) => {
    this.setState({
      selectedUserRows: rows,
    });
  }

  renderContent = (currentStep, formVals, records) => {
    const {form, usersData, orgTree, queryOrgTree, queryUserList, loading, orgAdmin, auditSetting,} = this.props;
    const {orgId, selectedUserRows, selectedRowKeys} = this.state;
    const usersChildren = [];
    const fileNames = records.map((item) => {
      return item.dirName;
    }).join(",");

    let auditUsers = [];
    if (orgAdmin) {
      orgAdmin.forEach(item => {
        auditUsers.push(<Option key={item.userCode}>{item.userName}</Option>);
      });
    }


    const userSelectMethods = {
      queryOrgTree: queryOrgTree,
      queryUserList: queryUserList,
      handleSelectUserRows: this.handleSelectUserRows,
    };


    if (currentStep === 1) {
      return <UserSelect {...userSelectMethods} orgTree={orgTree} usersData={usersData} loading={loading}/>;
    }
    if (currentStep === 2) {
      let receivers = "";
      selectedUserRows.map((item) => {
        if (receivers) {
          receivers = receivers + "," + item.userName;
        } else {
          receivers = item.userName;
        }
      });
      // const rightArray =formVals.rightConfig?formVals.rightConfig.split(","):[];

      // {/*<FormItem  {...this.formLayout} label="权限管控">*/},
      // {/*<CheckboxGroup disabled value={formVals.rightConfig} options={RightOptions}/>*/},
      // {/*</FormItem>,*/},
      return (
        <Form>
          <FormItem {...this.formLayout} label="文件名称">
            {fileNames}
          </FormItem>
          <FormItem {...this.formLayout} label="流转事项">
            {formVals.applyTitle}
          </FormItem>
          <FormItem {...this.formLayout} label="流转理由">
            {formVals.applyReason}
          </FormItem>
          <FormItem {...this.formLayout} label="接收人">
            {receivers}
          </FormItem>
        </Form>

      );
    }
    // {/*<FormItem key="rightConfig" {...this.formLayout} label="权限管控">*/}
    // {/*{form.getFieldDecorator('rightConfig', {*/}
    // {/*rules: [{required: false, message: '请选择至少一个！'}],*/}
    // {/*initialValue: formVals.waterType,*/}
    // {/*})(<CheckboxGroup options={RightOptions}/>)}*/}
    // {/*</FormItem>,*/}

    let formArrays = [];
    let nameForm = <FormItem key="fileName" {...this.formLayout} label="文件名称">
      {fileNames}
    </FormItem>;

    let titleForm = <FormItem key="name" {...this.formLayout} label="流转事项">
      {form.getFieldDecorator('applyTitle', {
        rules: [{required: true, message: '请输入流转事项！'}, {max: nameMaxLength()[0], message: nameMaxLength()[1]}],
        initialValue: formVals.applyTitle,
      })(<Input placeholder="请输入"/>)}
    </FormItem>;

    let reasonForm = <FormItem key="desc" {...this.formLayout} label="流转理由">
      {form.getFieldDecorator('applyReason', {
        rules: [{required: true, message: '请输入至少五个字符的流转理由！', min: 5}, {
          max: remarkMaxLength()[0],
          message: remarkMaxLength()[1]
        }],
        initialValue: formVals.applyReason,
      })(<TextArea rows={4} placeholder="请输入至少五个字符"/>)}
    </FormItem>;

    formArrays.push(nameForm);
    formArrays.push(titleForm);
    formArrays.push(reasonForm);

    if (auditSetting == 1) {
      let auditForm = < FormItem label="选择审批人" {...this.formLayout} >
        {form.getFieldDecorator('auditUserCode', {
          rules: [{required: true, message: '请选择审批人',},],
        })(
          <Select
            style={{width: '100%'}}
            placeholder="选择审批人"
          >
            {auditUsers}
          </Select>
        )
        }
      </FormItem>;
      formArrays.push(auditForm);
    }


    return formArrays;
  };

  renderFooter = currentStep => {
    const {handleFlowModalVisible, records, submitting,} = this.props;
    if (currentStep === 1) {
      return [
        <Button key="back" style={{float: 'left'}} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleFlowModalVisible(false, records)}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 2) {
      return [
        <Button key="back" style={{float: 'left'}} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleFlowModalVisible(false)}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)} loading={submitting}>
          完成
        </Button>,
      ];
    }
    return [
      <Button key="cancel" onClick={() => handleFlowModalVisible(false)}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
        下一步
      </Button>,
    ];
  };

  render() {
    const {handleFlowModalVisible, modalVisible, records, loading, auditSetting,} = this.props;
    //当前页面状态
    const {currentStep, formVals} = this.state;

    return (
      <Modal
        width={1000}
        bodyStyle={{padding: '32px 40px 48px'}}
        destroyOnClose
        title="文件流转"
        visible={modalVisible}
        footer={this.renderFooter(currentStep)}
        onCancel={() => handleFlowModalVisible(false)}
        afterClose={() => handleFlowModalVisible()}
        maskClosable={false}
        loading={loading}
      >
        <Steps style={{marginBottom: 28}} size="small" current={currentStep}>
          <Step title="流转事项"/>
          <Step title="选择接收人"/>
          <Step title="确认"/>

        </Steps>
        {this.renderContent(currentStep, formVals, records)}
      </Modal>
    );
  }
}

export default FlowCreateForm;
